import time

from flask import Flask, request, g, render_template
from flask_wtf.csrf import CSRFProtect

from config import config_settings
from models.base import db
from rules.system_user_rule import search_system_user
from flask_login import LoginManager


def init_app():
    flask_app = Flask(__name__, template_folder='../templates', static_folder='../static')
    flask_app.config.from_object(config_settings)

    login_manager = LoginManager()
    login_manager.login_view = 'admin_login.login'
    login_manager.login_message = '登录过期'
    login_manager.init_app(flask_app)

    @login_manager.user_loader
    def user_loader(user_id):
        return search_system_user(int(user_id))

    from .routes import setup_routes
    setup_routes(flask_app)

    return flask_app


def on_before_request():
    request.request_start_time = time.time()


def on_after_request(response):
    # if settings.OUT_CORS:
    #     set_cors_headers(response)
    return response


def on_teardown_app_context(response_or_exc):
    """
    不管是否有异常，注册的函数都会在每次请求之后执行。
    """

    actual_exception = getattr(g, 'exception_occurred', None) or response_or_exc
    if actual_exception:
        db.session.rollback()
        print('发生异常，事务已回滚')

    db.session.close()
    db.engine.dispose()
    return response_or_exc

app = init_app()
csrf = CSRFProtect(app)
db.init_app(app)

app.teardown_appcontext(on_teardown_app_context)
# apps.before_request(on_before_request)
# apps.after_request(on_after_request)

@app.errorhandler(404)
def handle_404(error):
    return render_template('404.html'), 404

# 初始化Celery
# celery = make_celery(app)

app.app_context().push()
